<template>
  <div class="episode_Box">
    <el-form
      ref="ruleFormRef"
      :model="formData"
      :rules="rules"
      label-position="left"
      label-width="140px"
      class="form_box"
    >
      <el-row>
        <el-col :span="18">
          <el-form-item label="剧目名称" prop="name">
            <el-input
              v-model="formData.name"
              placeholder="请输入昵称"
              maxlength="20"
              show-word-limit
              clearable
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="18">
          <el-form-item label="剧目海报" prop="cover" class="cover_box">
            <uploadFile @updateFileList="seccessFile" v-if="type == 'add'" />
            <div v-else :class="{ img_box: editType == 1 }">
              <template v-if="editType == 1 && formData?.cover">
                <el-image
                  style="height: 100px; border-radius: 4px"
                  :src="coverImg"
                  :zoom-rate="1.2"
                  :preview-src-list="[coverImg]"
                  :initial-index="1"
                  fit="contain"
                />
                <el-icon @click="deleteImg" class="delete_icon">
                  <CircleClose />
                </el-icon>
              </template>
              <uploadFile v-else @updateFileList="seccessFile" />
            </div>
            <p style="font-size: 12px; color: #969696">
              支持jpeg/jpg/png格式，图片建议使用450 * 660尺寸，文件大小 2Mb 以内
            </p>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="18">
          <el-form-item label="短剧推荐语" prop="recommend">
            <el-input
              v-model="formData.recommend"
              placeholder="请输入短剧推荐语"
              clearable
              maxlength="12"
              show-word-limit
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="18">
          <el-form-item label="剧目简介" prop="desc">
            <el-input
              v-model="formData.desc"
              placeholder="剧目简介"
              :rows="2"
              type="textarea"
              clearable
              maxlength="200"
              show-word-limit
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="18">
          <el-form-item label="标 签" prop="tagIds">
            <el-select
              v-model="formData.tagIds"
              filterable
              multiple
              collapse-tags
              collapse-tags-tooltip
              placeholder="请选择"
              clearable
            >
              <el-option
                v-for="item in tagsOption"
                :key="item?.id"
                :label="item.text"
                :value="item?.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="18">
          <el-form-item label="发行年份" prop="releaseYear">
            <el-date-picker
              v-model="formData.releaseYear"
              type="year"
              format="YYYY"
              value-format="YYYY"
              placeholder="请选择年份"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="18">
          <el-form-item label="备案类型" prop="recordType">
            <el-radio-group v-model="formData.recordType" @change="changeRadio">
              <el-radio :label="1">网络剧片发行许可证</el-radio>
              <el-radio :label="2">剧目备案号</el-radio>
              <el-radio :label="3">普通备案号</el-radio>
              <el-radio :label="4">重点备案号</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="18">
          <el-form-item label="备案信息" prop="recordInfo">
            <el-input
              v-model="formData.recordInfo"
              :placeholder="placehold"
              clearable
              maxlength="30"
              show-word-limit
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="18">
          <el-form-item label="总集数" prop="episodeNum">
            <el-input-number
              v-model="formData.episodeNum"
              size="large"
              :min="1"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="18">
          <el-form-item label="短剧更新状态" prop="status">
            <el-radio-group v-model="formData.status">
              <el-radio :label="1">未上映</el-radio>
              <el-radio :label="2">更新中</el-radio>
              <el-radio :label="3">已完结</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="18">
          <el-form-item label="付费模式">
            <el-radio-group v-model="formData.coin">
              <el-radio :label="1">金币</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="18">
          <el-form-item label="最低单价(金币)" prop="unblockCoinAmountMinLimit">
            <el-input-number
              v-model="formData.unblockCoinAmountMinLimit"
              size="large"
              :min="1"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="18">
          <el-form-item label="默认单价(金币)" prop="unblockCoinAmount">
            <el-input-number
              v-model="formData.unblockCoinAmount"
              size="large"
              :min="1"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="18">
          <el-form-item label="最大收费卡点" prop="chargeEpisodeNoUpperLimit">
            <el-input-number
              v-model="formData.chargeEpisodeNoUpperLimit"
              size="large"
              :min="1"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="18">
          <el-form-item label="默认收费卡点" prop="chargeEpisodeNo">
            <el-input-number
              v-model="formData.chargeEpisodeNo"
              size="large"
              :min="1"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="18">
          <el-form-item label="全集最小金币数" prop="unlockOperaCoinMinLimit">
            <el-input-number
              v-model="formData.unlockOperaCoinMinLimit"
              size="large"
              :min="1"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="18">
          <el-form-item label="默认全集金币数" prop="unlockOperaCoin">
            <el-input-number
              v-model="formData.unlockOperaCoin"
              size="large"
              :min="1"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <!-- <el-row>
        <el-col :span="18">
          <el-form-item label="小程序列展示" prop="password">
            <el-switch v-model="formData.value1" />
          </el-form-item>
        </el-col>
      </el-row> -->
      <el-row>
        <el-col :span="18">
          <el-form-item label="首播时间" prop="premiereTime">
            <el-date-picker
              v-model="formData.premiereTime"
              type="datetime"
              placeholder="请选择时间"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="18">
          <el-form-item label="开始投放时间" prop="promotionStartTime">
            <el-date-picker
              v-model="formData.promotionStartTime"
              type="datetime"
              placeholder="请选择时间"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="18">
          <el-form-item label="">
            <el-button type="primary" @click="config(ruleFormRef)">
              确 认
            </el-button>
            <el-button @click="cancel(ruleFormRef)">取 消</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </div>
</template>

<script lang="ts" setup>
import request from "@/utils/request";
import { ref, reactive, onMounted, computed } from "vue";
import {
  operasTags,
  addOperas,
  updateOperas,
  operasDetail,
  reviewCover,
} from "@/api/operateCenter/episode/index";
import type { FormInstance } from "element-plus";
import router from "@/router";
import { useRoute } from "vue-router";
import { cloneDeep } from "lodash-es";
import moment from "moment";
import uploadFile from "@/components/UploadFile/index.vue";
import { CircleClose } from "@element-plus/icons-vue";

const route = useRoute();

const ruleFormRef = ref<FormInstance>();
const props = defineProps({
  // 类型  add: 新增  update: 更新
  type: String,
});

const form = {
  id: undefined,
  name: "", // 剧集名称
  desc: "", // 剧集简介
  cover: "", // 封面图地址
  recommend: "", // 推荐语
  releaseYear: undefined, // 发行年份
  recordType: undefined, // 备案类型 1 - 许可证号， 2 - 登记号， 3 - 普通备案号， 4 - 重点备案号
  recordInfo: "", // 备案信息，如备案号
  episodeNum: undefined, // 分集数量
  status: undefined, // 短剧更新状态 1 - 未上映, 2 - 更新中 3 - 已完结
  unblockCoinAmount: undefined, // 解锁每集价格
  unblockCoinAmountMinLimit: undefined, // 解锁每集价格最低限额
  chargeEpisodeNo: undefined, // 开始付费集数
  chargeEpisodeNoUpperLimit: undefined, // 开始付费集数上限
  unlockOperaCoin: undefined, // 解锁全集金币数
  unlockOperaCoinMinLimit: undefined, // 解锁全集金币数最低限额
  premiereTime: "", // 首播时间
  promotionStartTime: "", // 开始投放时间
  tagIds: [], // 标签列表 - 最大支持3个标签
  coin: 1,
};
const formData = ref(Object.assign({}, form));
const tagsOption = ref<Array<any>>([]);
const fileData = ref<any>();
const editType = ref(1); // 1:未修改图片  2： 重新上传
const randN = Math.floor(Math.random() * 100000); // 生成随机数，保证每个图片不走浏览器缓存
const coverImg = ref<string>("");
const placehold = ref<string>("");

const changeRadio = (no: any) => {
  if (no === 1) {
    placehold.value =
      "请填写网络剧片发行许可证号。如：（沪）网剧审字（2023）第001号";
  } else if (no === 2) {
    placehold.value = "请填写剧目备案号。如：V45001234567894";
  } else if (no === 3) {
    placehold.value = "请填写普通备案号。如：粤ICP备20249999号";
  } else if (no === 4) {
    placehold.value = "请填写重点备案号。如：粤JJ—T00001";
  }
  // console.log("hode*----", placehold.value);
};

const fileRules = (rule: any, value: any, callback: any) => {
  if (rule.field == "unblockCoinAmount") {
    let limitAmout = formData.value.unblockCoinAmountMinLimit;
    if (!value) {
      return callback(new Error("请输入默认单价"));
    } else if (limitAmout && value < limitAmout) {
      value = undefined;
      return callback(new Error("默认单价不能低于最低单价"));
    }
    callback();
  } else if (rule.field == "chargeEpisodeNo") {
    let maxepisodeNum = formData.value.chargeEpisodeNoUpperLimit;
    if (!value) {
      return callback(new Error("请输入默认收费卡点"));
    } else if (maxepisodeNum && value > maxepisodeNum) {
      value = undefined;
      return callback(new Error("默认收费卡点不能大于最大收费卡点"));
    }
    callback();
  } else if (rule.field == "unlockOperaCoin") {
    let minCoin = formData.value.unlockOperaCoinMinLimit;
    if (!value) {
      return callback(new Error("请输入默认解锁全集金币数"));
    } else if (minCoin && value < minCoin) {
      value = undefined;
      return callback(
        new Error("默认解锁全集金币数不能低于解锁全集最小金币数")
      );
    }
    callback();
  } else if (rule.field == "tagIds") {
    if (!value.length) {
      return callback(new Error("请选择标签"));
    } else if (value.length > 3) {
      value = undefined;
      return callback(new Error("标签最多选择3个"));
    }
    callback();
  }
};
const rules = reactive({
  name: [{ required: true, message: "请输入昵称", trigger: "blur" }],
  // cover: [{ required: true, message: "请选择海报", trigger: "change" }],
  desc: [{ required: true, message: "请输入剧目简介", trigger: "blur" }],
  recommend: [{ required: true, message: "请输入短剧推荐语", trigger: "blur" }],
  releaseYear: [{ required: true, message: "请选择年份", trigger: "blur" }],
  recordType: [
    { required: true, message: "请选择备案类型", trigger: "change" },
  ],
  recordInfo: [{ required: true, message: "请输入备案信息", trigger: "blur" }],
  episodeNum: [{ required: true, message: "请输入总集数", trigger: "blur" }],
  status: [
    { required: true, message: "请选择短剧更新状态", trigger: "change" },
  ],
  unblockCoinAmount: [
    { required: true, validator: fileRules, trigger: "blur" },
  ],
  unblockCoinAmountMinLimit: [
    { required: true, message: "请输入最低单价", trigger: "blur" },
  ],
  chargeEpisodeNo: [{ required: true, validator: fileRules, trigger: "blur" }],
  chargeEpisodeNoUpperLimit: [
    { required: true, message: "请输入最大收费卡点", trigger: "blur" },
  ],
  unlockOperaCoin: [{ required: true, validator: fileRules, trigger: "blur" }],
  unlockOperaCoinMinLimit: [
    { required: true, message: "请输入解锁全集最小金币数", trigger: "blur" },
  ],
  premiereTime: [
    { required: true, message: "请选择首播时间", trigger: "blur" },
  ],
  promotionStartTime: [
    { required: true, message: "请选择投放时间", trigger: "blur" },
  ],
  tagIds: [{ required: true, validator: fileRules, trigger: "change" }],
});

// 文件长传
const seccessFile = (file: Array<any>) => {
  // console.log("file------", file);
  if (!file.length) {
    fileData.value = "";
  } else {
    fileData.value = file[0].raw;
  }
};

const deleteImg = () => {
  editType.value = 2;
};

// 确认
const config = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.validate((valid) => {
    if (valid) {
      let URL;
      if (props.type == "update") {
        URL = updateOperas;
      } else {
        URL = addOperas;
      }
      let params = cloneDeep(formData.value);
      params.releaseYear = (
        params?.releaseYear ? +params?.releaseYear : undefined
      ) as undefined;
      if (props.type === "add" && !fileData.value) {
        return ElMessage.error("请上传剧目海报");
      }
      // 后端接收utc国际时间 （-8h）
      params.premiereTime = moment(params.premiereTime)
        .utc()
        .format("YYYY-MM-DDTHH:mm:ss");

      params.promotionStartTime = moment(params.promotionStartTime)
        .utc()
        .format("YYYY-MM-DDTHH:mm:ss");

      URL(params).then((res: Record<string, any>) => {
        // 提交成功后获取到剧目id，和文件上传一起提交
        if (!fileData.value && props.type === "update") {
          ElMessage.success(`修改成功`);
          router.push("/operate/episode-list");
        } else {
          let id = props.type === "update" ? formData.value.id : res.data;
          submitConfig(id);
        }
      });
    }
  });
};

// 上传文件
const submitConfig = async (id: number) => {
  const formData = new FormData();
  formData.append("file", fileData.value);
  request.put(`/api/operation/Operas/${id}/cover`, formData).then(() => {
    ElMessage.success(`${props.type == "add" ? "添加" : "修改"}成功`);
    router.push("/operate/episode-list");
  });
};

// 取消
const cancel = (formEl: FormInstance | undefined) => {
  router.back();
};

// 剧目详情
const getOperasDetail = (id: number) => {
  operasDetail(id).then((res: any) => {
    res.coin = 1;
    formData.value = cloneDeep(res);
    formData.value.unlockOperaCoin = res?.unlockOperaCoin || undefined;
    formData.value.unlockOperaCoinMinLimit =
      res?.unlockOperaCoinMinLimit || undefined;
    formData.value.releaseYear = res?.releaseYear.toString();
    coverImg.value = `https://theater-static-1320245876.cos.ap-guangzhou.myqcloud.com/static/cover/${formData.value?.cover}?${randN}`;
    formData.value.premiereTime = moment(
      formData.value.premiereTime + "Z"
    ).format("YYYY-MM-DDTHH:mm:ss");
    formData.value.promotionStartTime = moment(
      formData.value.promotionStartTime + "Z"
    ).format("YYYY-MM-DDTHH:mm:ss");
    // console.log("xiangiqng 详情-----", formData.value);
  });
};

// 获取标签下拉选项
const getTags = () => {
  operasTags().then((res: any) => {
    tagsOption.value = res || [];
  });
};

onMounted(() => {
  getTags();
  let id = route.query?.id || undefined;
  if (id) {
    getOperasDetail(Number(id));
  }
});
</script>
<style scoped lang="scss">
.episode_Box {
  padding: 30px;
  background-color: #fff;

  .img_box {
    position: relative;
    display: flex;
    align-items: center;
    // height: 100px;
    border: 1px solid #dcdfe6;
    border-radius: 6px;

    .delete_icon {
      position: absolute;
      top: 3px;
      right: 0;
      color: #666;
      cursor: pointer;
    }
  }

  .cover_box {
    :deep(.el-form-item__content) {
      flex-direction: column;
      align-items: flex-start;
    }
  }
}
</style>
